package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.doc.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    //搜索栏自动补全
    @Override
    public List<String> itemSuggestion(String key) {
        try {
            SearchRequest request = new SearchRequest("item");
            request.source().suggest(new SuggestBuilder().addSuggestion("sug",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(key).size(20).skipDuplicates(true)));

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion sug = suggest.getSuggestion("sug");
            List<CompletionSuggestion.Entry.Option> options = sug.getOptions();
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //过滤项聚合
    @Override
    public Map<String, List<String>> itemFilters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("item");
            itemQuery(requestParams, request);
            request.source().size(0);
            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(100));

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String,List<String>> map = new HashMap<>();
            List<String> brandAgg = getAnalyze(response, "brandAgg");
            map.put("brand",brandAgg);
            List<String> categoryAgg = getAnalyze(response, "categoryAgg");
            map.put("category",categoryAgg);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //基本搜索功能
    @Override
    public PageDTO<ItemDoc> itemList(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("item");

            itemQuery(requestParams, request);

            //分页
            Integer page = requestParams.getPage();
            Integer size = requestParams.getSize();
            request.source().from((page - 1) * size).size(size);

            //排序
            String sortBy = requestParams.getSortBy();
            if (sortBy != null && !sortBy.equals("default")){
                request.source().sort(sortBy, SortOrder.DESC);
            }

            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return itemResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //删除商品
    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("item",id.toString());
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw  new RuntimeException(e);
        }
    }

    //新增或修改商品
    @Override
    public void updateAndInsertById(Long id) {
        try {
            Item item = itemClient.itemByID(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String toJSONString = JSON.toJSONString(itemDoc);
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            request.source(toJSONString, XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void itemQuery(RequestParams requestParams, SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = requestParams.getKey();
        if (key == null ||key.equals("")){
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",key));
        }
        if (requestParams.getBrand() != null && !requestParams.getBrand().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",requestParams.getBrand()));
        }
        if (requestParams.getCategory() != null && !requestParams.getCategory().equals("")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category",requestParams.getCategory()));
        }
        if (requestParams.getMaxPrice() != null && requestParams.getMinPrice() != null){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price")
                    .lte(requestParams.getMaxPrice()).gte(requestParams.getMinPrice()));
        }

        //竞价排名
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });
        request.source().query(functionScoreQueryBuilder);
    }

    //搜索功能结果解析
    private PageDTO<ItemDoc> itemResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        long value = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<ItemDoc> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                HighlightField field = highlightFields.get("name");
                if (field != null){
                    String name = field.getFragments()[0].string();
                    itemDoc.setName(name);
                }
            }
            list.add(itemDoc);
        }
        return new PageDTO<ItemDoc>(value,list);
    }

    //解析过滤项聚合
    private List<String> getAnalyze(SearchResponse response,String name) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }
}
